using System;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;

namespace DiskGarden
{
	public partial class FrmWait : Form
	{
		protected static FrmWait frmWait;
		protected static Form frmParent;
		protected static Thread thread;
		protected static string infoText;

		public string InfoText
		{
			get { return txtInfo.Text; }
			set
			{
				txtInfo.Text = value;
				txtInfo.Invalidate();
				Application.DoEvents();
			}
		}

		public FrmWait()
		{
			InitializeComponent();
			Localize();
		}

		private void Localize()
		{
			Locale locale = Locale.GetInstance();
			this.Text = locale.PleaseWait;
			txtInfo.Text = locale.PleaseWaitCataloguing;
		}

		private static void ShowForm()
		{
			Application.DoEvents();
			frmWait = new FrmWait();
			if (frmParent != null)
			{
				frmWait.Top = frmParent.Top + frmParent.Height / 2 - frmWait.Height / 2;
				frmWait.Left = frmParent.Left + frmParent.Width / 2 - frmWait.Width / 2;
			}
			else
			{
				frmWait.StartPosition = FormStartPosition.CenterScreen;
			}
			frmWait.InfoText = infoText;
			frmWait.ShowDialog();
		}

		public static void Start(Form frmParent)
		{
			Start(frmParent, Locale.GetInstance().PleaseWaitCataloguing);
		}

		public static void Start(Form frmParent, string info)
		{
			if (IsStarted())
				Stop();
			FrmWait.frmParent = frmParent;
			FrmWait.infoText = info;
			thread = new Thread(new ThreadStart(ShowForm));
			thread.IsBackground = true;
			thread.Priority = ThreadPriority.AboveNormal;
			thread.SetApartmentState(ApartmentState.MTA);
			thread.Start();
		}

		delegate void CloseForm();

		public static void Stop()
		{
			if (frmWait != null)
			{
				if (frmWait.InvokeRequired)
					frmWait.Invoke(new CloseForm(frmWait.Close));
				else
					frmWait.Close();
				frmWait = null;
				frmParent = null;
				thread = null;
			}
		}

		delegate void SetInfoCallback(string info);

		public static void SetInfo(string info)
		{
			if (frmWait != null)
			{
				if (frmWait.InvokeRequired)
					frmWait.Invoke(new SetInfoCallback(SetInfo), info);
				else
					frmWait.InfoText = info;
			}
		}

		public static bool IsStarted()
		{
			return (thread != null && frmWait != null);
		}
	}
}
